/**
 *
 */
package edu.berkeley.bps.services.corpus;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author pschmitz
 *
 */
public class XMLUtils {
	static final Logger logger = LoggerFactory.getLogger(XMLUtils.class);
			
	public static org.w3c.dom.Document OpenXMLFile(String filename) {
		return OpenXML(filename, null);
	}
	
	public static org.w3c.dom.Document OpenXMLStream(InputStream xmlStream) {
		return OpenXML(null, xmlStream);
	}
	
	private static org.w3c.dom.Document OpenXML(String filename, InputStream xmlStream) {
		org.w3c.dom.Document newDoc = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			if(filename!=null)
				newDoc = builder.parse(filename);
			else
				newDoc = builder.parse(xmlStream);
        } catch (SAXParseException spe) {
            // Error generated by the parser
            logger.error("\n** Parsing error, line {}, uri {}", spe.getLineNumber(), spe.getSystemId());
            logger.error("   {}", spe.getMessage());
            // Use the contained exception, if any
            Exception x = spe;
            if (spe.getException() != null) {
                x = spe.getException();
            }
            x.printStackTrace();
        } catch (SAXException sxe) {
            // Error generated by this application
            // (or a parser-initialization error)
            logger.error("SAX error: {}", sxe.getMessage());
            Exception x = sxe;
            if (sxe.getException() != null) {
                x = sxe.getException();
            }
            x.printStackTrace();
		} catch( ParserConfigurationException pce ) {
			logger.error("Parser Cfg error: {}", pce.getMessage());
            pce.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
        	logger.error("IO error: {}", ioe.getMessage());
            ioe.printStackTrace();
		} catch( RuntimeException e ) {
			logger.error(e.getMessage());
            e.printStackTrace();
		}
		return newDoc;
	}
}
